<template>
  <quill-editor class="editor"
                ref="myTextEditor"
                v-model:content="value"
                contentType="html"
                :options="editorOption">
  </quill-editor>
<!--  <div @click="getContent">{{ props.modelValue }}</div>-->
</template>
<script setup>
import {computed, onMounted, ref} from "vue";
import {QuillEditor} from '@vueup/vue-quill'
//富文本编辑器必要的三个文件，不引入无法显示编辑器
import hljs from 'highlight.js'
//代码高亮引入
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import 'highlight.js/styles/atom-one-dark.css'
//代码高亮样式，可自选

const props = defineProps({
  modelValue: {
    default: ''
  }
})
const emit = defineEmits(['update:modelValue'])

console.log(props);

//代码高亮配置
const highlightCode = () => {
  const pre = document.querySelectorAll('pre.ql-syntax');
  //选择所有pre标签并且class为ql-syntax的元素
  pre.forEach((el) => {
    hljs.highlightBlock(el);
    //渲染全部指定的标签
  })
}
const toolbarOptions = [
  ['bold', 'link', 'italic', 'underline', 'strike'],        // 切换按钮
  ['blockquote', 'code', 'code-block', 'image', 'video', 'formula'],
  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'script': 'sub'}, {'script': 'super'}],      // 上标/下标
  [{'indent': '-1'}, {'indent': '+1'}],          // 减少缩进/缩进
  [{'direction': 'rtl'}],                         // 文本下划线
  [{'size': ['small', false, 'large', 'huge']}],  // 用户自定义下拉
  [{'header': [1, 2, 3, 4, 5, 6, false]}],
  [{'color': []}, {'background': []}],
  [{'font': []}],
  [{'align': []}],
  ['clean']                                         // 清除格式
]

// let content = ref(``);//编辑器的内容
let editorOption = ref({        //编辑器配置
  modules: {
    syntax: {
      highlight: text => hljs.highlightAuto(text).value    // 语法高亮插件调用
    },
    toolbar: {
      container: toolbarOptions,  // 工具栏
      handlers: {
        'image': (value) => {//图片上传功能
          if (value) {
            var Imageinput = document.createElement('input');
            Imageinput.setAttribute('type', 'file');
            Imageinput.setAttribute('name', 'file');
            Imageinput.setAttribute('multiple', 'multiple');
            Imageinput.setAttribute('accept', 'image/png, image/gif, image/jpeg');
            Imageinput.classList.add('ql-image');
            Imageinput.addEventListener('change', () => {
              var file = Imageinput.files;
              var formData = new FormData();
              for (var i in file) {
                formData.append("file[]", file[i]);
              }
              if (Imageinput.files != null) {
                //图片上传接口  Upload
                this.ajax.post("/Upload", formData, "file")
                    .then(data => {
                      if (data.data.code == 200) {
                        //接口返回200，把返回的图片地址渲染上去
                        this.handleSuccess(data.data)
                      } else {
                        console.log("图片上传失败");
                      }
                    })
              }
            });
            Imageinput.click();
          } else {
            this.quill.format('image', false);
            //取消上传图片
          }
        }
      },
    }
  }
});
let myTextEditor = ref();
let value = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

const handleSuccess = (data) => {
  for (var img of data.data) {
    //遍历数组的图片地址并渲染
    let quill = myTextEditor.value.quill
    let length = quill.getSelection().index;
    quill.insertEmbed(length, 'image', img)
    quill.setSelection(length + 1)
    //把图片添加到光标处
  }
}

const getContent = () => {

}

</script>
